const Product = require('../models/product.model');
const Shop = require('../models/shop.model');
const mongoose = require('mongoose');

// 解析排序字符串为MongoDB排序对象
function parseSortString(sortStr) {
  const sortObj = {};
  if (sortStr.startsWith('-')) {
    sortObj[sortStr.substring(1)] = -1;
  } else {
    sortObj[sortStr] = 1;
  }
  return sortObj;
}

/**
 * 获取商品列表 (管理员)
 * GET /api/admin/products
 */
exports.getProducts = async (req, res, next) => {
  try {
    const {
      keyword = '',
      category = '',
      status = '',
      shopId = '',
      page = 1,
      limit = 10,
      sort = '-createdAt',
      minPrice,
      maxPrice,
      isFeatured
    } = req.query;

    // 构建查询条件
    const query = {};

    // 关键词搜索
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } },
        { brand: { $regex: keyword, $options: 'i' } },
        { category: { $regex: keyword, $options: 'i' } },
        { tags: { $in: [new RegExp(keyword, 'i')] } }
      ];
    }

    // 分类过滤
    if (category) {
      query.category = category;
    }

    // 状态过滤
    if (status) {
      if (status === 'out_of_stock') {
        query.stock = 0;
      } else {
        query.status = status;
      }
    }

    // 店铺过滤
    if (shopId) {
      query.shop = shopId;
    }

    // 价格过滤
    if (minPrice !== undefined || maxPrice !== undefined) {
      query.price = {};
      if (minPrice !== undefined) query.price.$gte = Number(minPrice);
      if (maxPrice !== undefined) query.price.$lte = Number(maxPrice);
    }

    // 推荐商品过滤
    if (isFeatured !== undefined) {
      query.isFeatured = isFeatured === 'true';
    }

    // 分页
    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 简化查询，避免复杂聚合导致的性能问题
    console.log('查询条件:', query);

    // 获取总数
    const total = await Product.countDocuments(query);
    console.log('商品总数:', total);

    // 获取商品数据
    const products = await Product.find(query)
      .populate('shop', 'name logo type rating.overall')
      .sort(parseSortString(sort))
      .skip(skip)
      .limit(limitNumber)
      .lean();

    console.log('查询到的商品数量:', products.length);

    // 格式化返回数据
    const formattedProducts = products.map(product => ({
      id: product._id,
      _id: product._id,
      name: product.name || '',
      description: product.description || '',
      price: product.price || 0,
      originalPrice: product.originalPrice || product.price || 0,
      images: product.images || [],
      category: product.category || '',
      brand: product.brand || '',
      stock: product.countInStock || 0,
      status: product.status || 'active',
      shopId: product.shop?._id || null,
      shopName: product.shop?.name || '',
      salesCount: product.salesCount || 0,
      isFeatured: product.isFeatured || false,
      tags: product.tags || [],
      specifications: product.specifications || {},
      createdAt: product.createdAt,
      updatedAt: product.updatedAt
    }));

    console.log('格式化后的商品数据样本:', formattedProducts.slice(0, 1));

    const response = {
      success: true,
      data: formattedProducts,
      pagination: {
        current: pageNumber,
        pageSize: limitNumber,
        total,
        pages: Math.ceil(total / limitNumber)
      },
      total
    };

    console.log('API响应结构:', {
      success: response.success,
      dataLength: response.data.length,
      total: response.total,
      pagination: response.pagination
    });

    res.json(response);
  } catch (error) {
    console.error('获取商品列表错误:', error);
    next(error);
  }
};

/**
 * 获取商品详情 (管理员)
 * GET /api/admin/products/:id
 */
exports.getProduct = async (req, res, next) => {
  try {
    const productId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(productId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商品ID'
      });
    }

    const product = await Product.findById(productId)
      .populate('shop', 'name logo type rating certification');

    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }

    res.json({
      success: true,
      data: {
        id: product._id,
        name: product.name,
        description: product.description,
        price: product.price,
        originalPrice: product.originalPrice,
        images: product.images,
        category: product.category,
        brand: product.brand,
        stock: product.stock || product.countInStock || 0,
        status: product.stock === 0 ? 'out_of_stock' : (product.status || 'active'),
        shopId: product.shop?._id,
        shopName: product.shop?.name,
        salesCount: product.salesCount || 0,
        isFeatured: product.isFeatured || false,
        tags: product.tags || [],
        specifications: product.specifications || {},
        createdAt: product.createdAt,
        updatedAt: product.updatedAt
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 创建商品 (管理员)
 * POST /api/admin/products
 */
exports.createProduct = async (req, res, next) => {
  try {
    const productData = {
      ...req.body,
      countInStock: req.body.stock || 0
    };

    // 自动设置mainImage为images数组的第一个图片
    if (productData.images && productData.images.length > 0 && !productData.mainImage) {
      productData.mainImage = productData.images[0];
    }

    const product = new Product(productData);
    await product.save();

    res.status(201).json({
      success: true,
      data: product,
      message: '商品创建成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新商品 (管理员)
 * PUT /api/admin/products/:id
 */
exports.updateProduct = async (req, res, next) => {
  try {
    const productId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(productId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商品ID'
      });
    }

    const updateData = { ...req.body };
    if (updateData.stock !== undefined) {
      updateData.countInStock = updateData.stock;
    }

    // 如果更新了images数组，自动更新mainImage
    if (updateData.images && updateData.images.length > 0) {
      // 如果没有明确设置mainImage，或者当前mainImage不在新的images数组中
      if (!updateData.mainImage || !updateData.images.includes(updateData.mainImage)) {
        updateData.mainImage = updateData.images[0];
      }
    }

    const product = await Product.findByIdAndUpdate(
      productId,
      updateData,
      { new: true, runValidators: true }
    ).populate('shop', 'name logo type rating');

    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }

    res.json({
      success: true,
      data: product,
      message: '商品更新成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除商品 (管理员)
 * DELETE /api/admin/products/:id
 */
exports.deleteProduct = async (req, res, next) => {
  try {
    const productId = req.params.id;

    if (!mongoose.Types.ObjectId.isValid(productId)) {
      return res.status(400).json({
        success: false,
        message: '无效的商品ID'
      });
    }

    const product = await Product.findByIdAndDelete(productId);

    if (!product) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }

    res.json({
      success: true,
      message: '商品删除成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 批量删除商品 (管理员)
 * POST /api/admin/products/batch-delete
 */
exports.batchDeleteProducts = async (req, res, next) => {
  try {
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的商品ID列表'
      });
    }

    const result = await Product.deleteMany({
      _id: { $in: ids }
    });

    res.json({
      success: true,
      message: `成功删除 ${result.deletedCount} 个商品`
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 批量更新商品 (管理员)
 * POST /api/admin/products/batch-update
 */
exports.batchUpdateProducts = async (req, res, next) => {
  try {
    const { ids, data } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的商品ID列表'
      });
    }

    const updateData = { ...data };
    if (updateData.stock !== undefined) {
      updateData.countInStock = updateData.stock;
    }

    const result = await Product.updateMany(
      { _id: { $in: ids } },
      updateData
    );

    res.json({
      success: true,
      message: `成功更新 ${result.modifiedCount} 个商品`
    });
  } catch (error) {
    next(error);
  }
};

module.exports = exports;
